package com.leapcloud.crm.core.model;

import com.leapcloud.crm.core.exception.ImsException;
import com.leapcloud.crm.core.utils.BeanUtils;
import com.leapcloud.crm.core.vo.PageVO;
import com.leapcloud.crm.core.exception.ImsException;
import com.leapcloud.crm.core.utils.BeanUtils;
import com.leapcloud.crm.core.vo.PageVO;
import lombok.Data;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author wangzhenyan
 * @email ffu@maxleap.com
 * @since 2018/8/29 13:40
 */
@Data
public class PageInfo<T> implements Serializable {
  //当前页数
  private int pageNum;

  //当前页条数
  private int pageSize;

  //总条数
  private long totalSize;

  //总页数
  private int totalPage;

  //是否存在下一页
  private boolean nextPage;

  //是否存在上一页
  private boolean prevPage;

  private List<T> list;

  public PageInfo() {
  }

  public PageInfo(PageVO pageVO) {
    this.pageNum = pageVO.getPageNum();
    this.pageSize = pageVO.getPageSize();
  }

  public PageInfo(int pageNum, int pageSize, long totalSize) {
    if (pageNum <= 0) {
      throw new ImsException("页数必须大于0");
    }
    if (pageSize <= 0 || pageSize > 500) {
      throw new ImsException("每页数据条数数必须大于0或小于500");
    }
    this.pageNum = pageNum;
    this.pageSize = pageSize;
    this.totalSize = totalSize;
    if (totalSize <= 0) {
      return;
    }
    int start = (pageNum - 1) * pageSize;
    if (start > pageSize) {
      this.prevPage = true;
    }
    if (totalSize > start + pageSize) {
      this.nextPage = true;
    }

    if (totalSize % pageSize == 0) {
      this.totalPage = (int) (totalSize / pageSize);
    } else {
      this.totalPage = (int) (totalSize / pageSize) + 1;
    }
  }

  public <DTO> PageInfo<DTO> toDTO(Class<DTO> dtoClass) {
    PageInfo<DTO> dtoPageInfo = BeanUtils.transfrom(PageInfo.class, this);
    List<DTO> list = this.list.stream().flatMap(t -> Stream.of(BeanUtils.transfrom(dtoClass, t))).collect(Collectors.toList());
    dtoPageInfo.setList(list);
    return dtoPageInfo;
  }
}
